/*
 * @lc app=leetcode.cn id=147 lang=javascript
 *
 * [147] 对链表进行插入排序
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var insertionSortList = function (head) {
  if (head === null) {
    return head;
  }

  const dummy = new ListNode(0);
  dummy.next = head;

  let sortedNode = head;
  let currNode = head.next;

  while (currNode !== null) {
    if (sortedNode.val <= currNode.val) {
      sortedNode = sortedNode.next;
    } else {
      let prevNode = dummy;
      while (prevNode.next.val <= currNode.val) {
        prevNode = prevNode.next;
      }
      sortedNode.next = currNode.next;
      currNode.next = prevNode.next;
      prevNode.next = currNode;
    }
    currNode = sortedNode.next;
  }

  return dummy.next;
};
// @lc code=end
